package com.ybkj.daijia.server.event.listener;

import com.ybkj.daijia.PushDataV4;
import com.ybkj.daijia.Setting;
import com.ybkj.daijia.serverUtils.SettingUtils;
import com.ybkj.daijia.api.gexin.GeTuiEmployV4;
import com.ybkj.daijia.api.jpush.JiGuangEmployV4;
import com.ybkj.daijia.server.event.model.OrderZhuandanEvent;
import com.ybkj.daijia.server.model.Company;
import com.ybkj.daijia.server.model.Driver;
import com.ybkj.daijia.server.model.Order;
import com.ybkj.daijia.server.model.SmsTemplet;
import com.ybkj.daijia.server.model.SmsTemplet.SmsType;
import com.ybkj.daijia.server.reactor.ReactorVo;
import com.ybkj.daijia.server.service.CompanyService;
import com.ybkj.daijia.server.service.DriverService;
import com.ybkj.daijia.server.service.OrderService;
import com.ybkj.daijia.server.service.SmsService;
import com.ybkj.daijia.server.service.SmsTempletService;
import com.ybkj.daijia.server.websocket.WebSocketSend;
import java.io.IOException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.HashMap;
import java.util.Map;
import org.apache.commons.lang3.StringUtils;
import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ApplicationEventMulticaster;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;

@Component
public class OrderZhuandanEventListener implements ApplicationListener<OrderZhuandanEvent> {

    private static final Logger logger = LoggerFactory.getLogger(OrderZhuandanEventListener.class);

    @Autowired
    private SmsTempletService smsTempletService;
    @Autowired
    private SmsService smsService;
    @Autowired
    private DriverService driverService;

    @Autowired
    private OrderService orderService;

    @Autowired
    private SettingUtils settingUtils;


    @Autowired
    private CompanyService companyService;

    @Autowired
    private ApplicationEventMulticaster applicationEventMulticaster;

    @Override
    @Async
    public void onApplicationEvent(OrderZhuandanEvent event) {

        ReactorVo vo = (ReactorVo) event.getSource();
        Order order = vo.getOrder();
        logger.debug("order paidan event:{}", order.getOrderNumber());
        Driver driver = driverService.findOne(order.getDriverId());
        Driver oldDriver = vo.getDriver();

//		int applyWorkCar = -1;
//		List<WorkCarPickup> wcps=workCarPickupService.listOldWjAndJsAndSc(driver.getId());
//		if(!CollectionUtils.isEmpty(wcps)){
//			if(wcps.get(0).getStatus()==WorkCarPickup.WORKCAR_WEIJIE || wcps.get(0).getStatus()==WorkCarPickup.WORKCAR_YIJIE){
//				applyWorkCar = WorkCarPickup.WORKCAR_WEIJIE;
//			}
//			else if(wcps.get(0).getStatus()==WorkCarPickup.WORKCAR_SHANGCHE){
//				applyWorkCar = WorkCarPickup.WORKCAR_YIJIE;
//			}
//		}

        //推送数据到浏览器
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("orderID", order.getId());
        jsonObject.put("orderNumber", order.getOrderNumber());
        jsonObject.put("driverID", driver.getId());
        jsonObject.put("isworkCar", driver.isWorkCar());

        if (oldDriver.getStatus().equals(Driver.DRIVER_ONLINE)) {
            jsonObject.put("oldDriverID", oldDriver.getId());
            jsonObject.put("oldIsworkCar", oldDriver.isWorkCar());
        }

        Company mainCompany = companyService.getMain();
        Company orderCompany = companyService.findOne(order.getCompanyId());
        //地区推送
        jsonObject.put("type", "zhuandan_area");
        WebSocketSend.boardcastToArea(jsonObject, orderCompany.getCityName(), mainCompany.getId());
        //对应公司推送
        jsonObject.put("type", "zhuandan_company");
        WebSocketSend.boardcastToCompany(jsonObject, order.getCompanyId(), mainCompany.getId());

        Setting setting = settingUtils.get();

        try {
            PushDataV4 pushDataV4 = new PushDataV4();
            pushDataV4.setCode("0X03");
            pushDataV4.setData(order.getId());
            pushDataV4.setType("0X00");
            pushDataV4.setSound("beep_3");
            Map<String, String> extra = new HashMap<String, String>();
            extra.put("content", "您有新的工单啦,单号:" + order.getOrderNumber() + ",赶快打开服务人员端接单吧");
            pushDataV4.setExtra(extra);

            boolean getuiOnline = false;
            if (StringUtils.isNotBlank(driver.getUserID())) {
                getuiOnline = GeTuiEmployV4.getClientOnline(driver.getUserID(), settingUtils.get());
            }

            if (getuiOnline) {
                GeTuiEmployV4.push(driver, pushDataV4, settingUtils.get());
            } else {
                if (StringUtils.isNotBlank(driver.getRegistrationId())) {
                    JiGuangEmployV4.push(driver, pushDataV4, settingUtils.get());
                }
            }

        } catch (IOException e) {
            logger.debug("push error : " + e.getMessage());
        }

        //发送短信
        Company driverCompany = companyService.findOne(driver.getCompanyId());
        if (setting.isSmsMainCompany()) {
            driverCompany = mainCompany;
        }

        try {
            SmsTemplet templet = smsService.findByAlias(driverCompany.getId(), SmsType.newOrder);
            if (null != templet && StringUtils.isNotBlank(templet.getContent())) {
                DateFormat format = new SimpleDateFormat("HH:mm");
                String serverTime = format.format(order.getServerTime());
                //smsService.sendSms(driver.getPhone(), "newOrder", "{\"订单号\":\""+"***"+order.getOrderNumber().substring(8)+"\",\"客户姓名\":\""+order.getClientName()+"\",\"客户电话\":\""+order.getClientPhone()+"\",\"预约时间\":\""+serverTime+"\",\"预约地点\":\""+order.getFromPlace()+"\"}", driverCompany.getId(), 0, driverCompany.getSignName());
                //短信发送（改）
                com.alibaba.fastjson.JSONObject smsParam = new com.alibaba.fastjson.JSONObject();
                smsParam.put("order", order.getOrderNumber().substring(8));
                smsParam.put("name", order.getClientName());
                smsParam.put("tel", order.getClientPhone());
                smsParam.put("serverTime", serverTime);
                smsParam.put("fromPlace", order.getFromPlace());
                smsService
                    .sendSms(driver.getPhone(), templet.getTemplateId(), smsParam.toJSONString(),
                        driverCompany.getId(), 0, driverCompany.getSignName());
            }
        } catch (Exception e) {
            logger.error("发送短信发生异常：{}", e.getMessage());
        }

    }


}
